package com.hong.zoo;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 改进后的Zookeeper分布式锁
 */
public class ZkDistributeImproveLock implements Lock{

    /**
     * 利用临时顺序节点来实现分布式锁
     * 获取锁:取排队号(创建自己的临时顺序节点),然后判断自己是否是最小号,如是,则获得锁;
     * 不是,则注册前一节点的watcher,阻塞等待
     * 释放锁:删除自己创建的临时顺序节点
     */
    private String lockPath; //现在的lockPath变成了父节点,且是个持久化节点

    private ZkClient client;

    private String currentPath;

    private String beforePath;

    public ZkDistributeImproveLock(String lockPath) {
        this.lockPath = lockPath;
        client = new ZkClient("localhost:2181");
        client.setZkSerializer(new MyZkSerializer());

        if (!this.client.exists(lockPath)){
            try {
                this.client.createPersistent(lockPath);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 如果获取不到锁,则阻塞等待
     */
    @Override
    public void lock() {
        if (!tryLock()){
            // 没获得锁,阻塞自己
            waitForLock();
            lock();
        }
    }

    /**
     *  注册节点的watcher,阻塞等待
     */
    private void waitForLock() {
        CountDownLatch cdl = new CountDownLatch(1);
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String lockPath, Object data) throws Exception {

            }

            @Override
            public void handleDataDeleted(String lockPath) throws Exception {
                System.out.println("===收到节点被删除了===");
                cdl.countDown();
            }
        };

        client.subscribeDataChanges(this.beforePath,listener);

        // 使用CountDownLatch cdl = new CountDownLatch(1);实现阻塞自己
        if (this.client.exists(this.beforePath)){
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 醒来后,取消注册
        client.unsubscribeDataChanges(this.beforePath,listener);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    /**
     * 非阻塞获取锁
     * @return
     */
    @Override
    public boolean tryLock() {
        if (this.currentPath == null){
            currentPath = this.client.createEphemeralSequential(lockPath + "/" , "number");
        }
        // 获得所有的子节点
        List<String> children = this.client.getChildren(lockPath);
        Collections.sort(children);

        //判断当前节点是否是最小的
        if (currentPath.equals(lockPath + "/" + children.get(0))){
            return true;
        }else {
            // 取到前一个,得到字节的索引号
            int curIndex = children.indexOf(currentPath.substring(lockPath.length() + 1));
            beforePath = lockPath + "/" + children.get(curIndex-1);
        }
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        client.delete(this.currentPath);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
